package cn.edu.gzu.user.controller;

import cn.edu.gzu.user.entity.UserEntity;
import cn.edu.gzu.user.result.Result;
import cn.edu.gzu.user.result.ResultCode;
import cn.edu.gzu.user.service.UserService;
import cn.edu.gzu.user.tool.FileUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.net.UnknownHostException;

@RestController
@RequestMapping("avatar")
public class AvatarController {
    @Value("${file.imagePath}")
    private String imagePath;

    @Resource(name = "userService")
    private UserService userService;

    /**
     * 保存
     */
    @CrossOrigin
    @RequestMapping("/update")
    public JSONObject save(MultipartFile file, String userId) throws UnknownHostException {
        long id = Integer.parseInt(userId);
        if (file == null) {
            System.out.println("文件为空！！");
            return Result.failure(ResultCode.FAILURE_INSERT_ERROR,"文件为空！");
        }
        UserEntity user = userService.getOne(new QueryWrapper<UserEntity>().eq("id",id));
        //加上用户标题命名，防止同名误删
        user.setAvatarUrl("http://192.168.43.176:9100/file/image/" + id +file.getOriginalFilename());
        boolean save = userService.updateById(user);

        if (save) {
            try {
                FileUtil.uploadFile(file.getBytes(), imagePath, id  + file.getOriginalFilename());
            } catch (Exception e) {
                e.printStackTrace();
                return Result.failure(ResultCode.FAILURE_INSERT_ERROR,"文件超过1000MB！");
            }
            return Result.success("上传成功");
        }
        return Result.failure(ResultCode.FAILURE_INSERT_ERROR,"上传失败");
    }
}
